package ynu.edu.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.dto.CartDTO;
import ynu.edu.dto.OrderDTO;
import ynu.edu.dto.OrderItemDTO;
import ynu.edu.dto.OrderRequestDTO;
import ynu.edu.entities.BaseResponse;
import ynu.edu.entity.CartEntity;
import ynu.edu.entity.OrderEntity;
import ynu.edu.entity.OrderItemEntity;
import ynu.edu.exception.ResourceNotFoundException;
import ynu.edu.feign.AddressFeignClient;
import ynu.edu.feign.FoodFeignClient;
import ynu.edu.feign.MerchantFeignClient;
import ynu.edu.repository.CartRepository;
import ynu.edu.repository.OrderItemRepository;
import ynu.edu.repository.OrderRepository;
import ynu.edu.service.CartService;
import ynu.edu.service.OrderService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单服务实现
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderItemRepository orderItemRepository;

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private CartService cartService;

    @Autowired
    private FoodFeignClient foodFeignClient;

    @Autowired
    private AddressFeignClient addressFeignClient;

    @Autowired
    private MerchantFeignClient merchantFeignClient;

    /**
     * 创建订单
     */
    @Override
    @Transactional
    public OrderDTO createOrder(OrderRequestDTO orderRequest) {
        try {
            System.out.println("开始创建订单，请求参数: " + orderRequest);
            
            // 1. 创建订单
            OrderEntity order = new OrderEntity();
            order.setUserId(orderRequest.getUserId());
            order.setBusinessId(orderRequest.getBusinessId());
            order.setOrderDate(LocalDateTime.now());
            order.setOrderTotal(orderRequest.getOrderTotal());
            order.setOrderState(0); // 待支付
            order.setDaId(orderRequest.getDaId());
            
            System.out.println("保存订单基本信息: " + order);
            OrderEntity savedOrder = orderRepository.save(order);
            System.out.println("订单基本信息保存成功，ID: " + savedOrder.getOrderId());
            
            List<OrderItemEntity> orderItems = new ArrayList<>();
            
            // 2. 处理订单明细
            if (orderRequest.getOrderDetails() != null && !orderRequest.getOrderDetails().isEmpty()) {
                System.out.println("处理订单明细，数量: " + orderRequest.getOrderDetails().size());
                
                for (OrderItemDTO detail : orderRequest.getOrderDetails()) {
                    System.out.println("处理订单项: " + detail);
                    
                    OrderItemEntity orderItem = new OrderItemEntity();
                    orderItem.setOrderId(savedOrder.getOrderId());
                    orderItem.setFoodId(detail.getFoodId());
                    orderItem.setQuantity(detail.getQuantity());
                    
                    orderItems.add(orderItem);
                    System.out.println("订单项处理完成: " + orderItem);
                }
            } else {
                // 从购物车创建订单
                System.out.println("从购物车创建订单");
                List<CartEntity> cartItems = cartRepository.findByUserId(orderRequest.getUserId());
                System.out.println("用户购物车项数量: " + cartItems.size());
                
                for (CartEntity cart : cartItems) {
                    System.out.println("处理购物车项: " + cart);
                    
                    OrderItemEntity orderItem = new OrderItemEntity();
                    orderItem.setOrderId(savedOrder.getOrderId());
                    orderItem.setFoodId(cart.getFoodId());
                    orderItem.setQuantity(cart.getQuantity());
                    
                    orderItems.add(orderItem);
                    System.out.println("订单项处理完成: " + orderItem);
                }
                
                // 3. 删除购物车项
                if (orderRequest.getCartIds() != null && !orderRequest.getCartIds().isEmpty()) {
                    System.out.println("删除购物车项: " + orderRequest.getCartIds());
                    cartRepository.deleteByCartIdIn(orderRequest.getCartIds());
                    System.out.println("购物车项删除成功");
                }
            }
            
            System.out.println("保存订单项，数量: " + orderItems.size());
            orderItemRepository.saveAll(orderItems);
            System.out.println("订单项保存成功");
            
            // 4. 构建返回对象
            System.out.println("获取完整订单信息: " + savedOrder.getOrderId());
            OrderDTO result = getOrderById(savedOrder.getOrderId());
            System.out.println("订单创建完成: " + result);
            
            return result;
        } catch (Exception e) {
            System.out.println("创建订单异常: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 获取订单详情
     */
    @Override
    public OrderDTO getOrderById(Integer orderId) {
        OrderEntity order = orderRepository.findById(orderId)
                .orElseThrow(() -> new ResourceNotFoundException("订单", "ID", orderId));
        
        return convertToDTO(order);
    }

    /**
     * 获取用户订单列表
     */
    @Override
    public List<OrderDTO> getOrdersByUserId(String userId) {
        List<OrderEntity> orders = orderRepository.findByUserIdOrderByOrderDateDesc(userId);
        return orders.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 获取用户特定状态的订单列表
     */
    @Override
    public List<OrderDTO> getOrdersByUserIdAndStatus(String userId, Integer orderState) {
        List<OrderEntity> orders = orderRepository.findByUserIdAndOrderStateOrderByOrderDateDesc(userId, orderState);
        return orders.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 更新订单状态
     */
    @Override
    @Transactional
    public OrderDTO updateOrderStatus(Integer orderId, Integer orderState) {
        OrderEntity order = orderRepository.findById(orderId)
                .orElseThrow(() -> new ResourceNotFoundException("订单", "ID", orderId));
        
        order.setOrderState(orderState);
        OrderEntity updatedOrder = orderRepository.save(order);
        
        return convertToDTO(updatedOrder);
    }

    /**
     * 取消订单
     */
    @Override
    @Transactional
    public OrderDTO cancelOrder(Integer orderId) {
        return updateOrderStatus(orderId, 1); // 已取消
    }

    /**
     * 支付订单
     */
    @Override
    @Transactional
    public OrderDTO payOrder(Integer orderId) {
        return updateOrderStatus(orderId, 2); // 已支付
    }

    /**
     * 完成订单
     */
    @Override
    @Transactional
    public OrderDTO completeOrder(Integer orderId) {
        return updateOrderStatus(orderId, 4); // 已完成
    }

    /**
     * 将订单实体转换为DTO
     */
    private OrderDTO convertToDTO(OrderEntity order) {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrderId(order.getOrderId());
        orderDTO.setUserId(order.getUserId());
        orderDTO.setBusinessId(order.getBusinessId());
        orderDTO.setOrderDate(order.getOrderDate());
        orderDTO.setOrderTotal(order.getOrderTotal());
        orderDTO.setOrderState(order.getOrderState());
        orderDTO.setDaId(order.getDaId());
        
        // 商家信息对象
        Map<String, Object> merchantInfo = new HashMap<>();
        merchantInfo.put("businessId", order.getBusinessId());
        
        // 食品信息映射
        Map<Integer, Map<String, Object>> foodMap = new HashMap<>();
        
        // 获取商家信息
        try {
            BaseResponse<Map<String, Object>> merchantResponse = merchantFeignClient.getMerchantById(order.getBusinessId());
            if (merchantResponse.getCode() == 200 && merchantResponse.getData() != null) {
                String businessName = (String) merchantResponse.getData().get("businessName");
                orderDTO.setBusinessName(businessName);
                merchantInfo.put("businessName", businessName);
                
                // 添加其他商家信息
                merchantInfo.putAll(merchantResponse.getData());
            } else {
                orderDTO.setBusinessName("未知商家");
                merchantInfo.put("businessName", "未知商家");
            }
        } catch (Exception e) {
            orderDTO.setBusinessName("未知商家");
            merchantInfo.put("businessName", "未知商家");
            System.out.println("获取商家信息失败: " + e.getMessage());
        }
        
        // 获取地址信息
        Map<String, Object> addressInfo = new HashMap<>();
        try {
            BaseResponse<Map<String, Object>> addressResponse = addressFeignClient.getAddressById(order.getDaId());
            if (addressResponse.getCode() == 200 && addressResponse.getData() != null) {
                String address = (String) addressResponse.getData().get("address");
                orderDTO.setAddress(address);
                addressInfo.putAll(addressResponse.getData());
            } else {
                orderDTO.setAddress("未知地址");
                addressInfo.put("address", "未知地址");
            }
        } catch (Exception e) {
            orderDTO.setAddress("未知地址");
            addressInfo.put("address", "未知地址");
            System.out.println("获取地址信息失败: " + e.getMessage());
        }
        
        // 获取订单项列表
        List<OrderItemEntity> orderItems = orderItemRepository.findByOrderId(order.getOrderId());
        List<OrderItemDTO> orderItemDTOs = new ArrayList<>();
        List<Map<String, Object>> orderDetails = new ArrayList<>();
        
        for (OrderItemEntity orderItem : orderItems) {
            OrderItemDTO itemDTO = new OrderItemDTO();
            itemDTO.setOrderItemId(orderItem.getOrderItemId());
            itemDTO.setOrderId(orderItem.getOrderId());
            itemDTO.setFoodId(orderItem.getFoodId());
            itemDTO.setQuantity(orderItem.getQuantity());
            
            // 创建订单明细对象（兼容前端格式）
            Map<String, Object> orderDetail = new HashMap<>();
            orderDetail.put("foodId", orderItem.getFoodId());
            orderDetail.put("quantity", orderItem.getQuantity());
            
            // 获取食品信息（名称、价格、图片）
            try {
                BaseResponse<Map<String, Object>> foodResponse = foodFeignClient.getFoodById(orderItem.getFoodId());
                if (foodResponse.getCode() == 200 && foodResponse.getData() != null) {
                    Map<String, Object> foodData = foodResponse.getData();
                    
                    // 设置食品名称
                    String foodName = (String) foodData.get("foodName");
                    itemDTO.setFoodName(foodName);
                    orderDetail.put("foodName", foodName);
                    
                    // 设置食品图片
                    String foodImg = (String) foodData.get("foodImg");
                    itemDTO.setFoodImg(foodImg);
                    orderDetail.put("foodImg", foodImg);
                    
                    // 处理价格
                    Object priceObj = foodData.get("foodPrice");
                    BigDecimal price = BigDecimal.ZERO;
                    if (priceObj instanceof Number) {
                        price = BigDecimal.valueOf(((Number) priceObj).doubleValue());
                    } else if (priceObj instanceof String) {
                        try {
                            price = new BigDecimal((String) priceObj);
                        } catch (Exception e) {
                            price = BigDecimal.TEN; // 默认价格
                        }
                    }
                    itemDTO.setFoodPrice(price);
                    orderDetail.put("foodPrice", price);
                    
                    // 计算小计
                    BigDecimal subtotal = price.multiply(new BigDecimal(orderItem.getQuantity()));
                    itemDTO.setSubtotal(subtotal);
                    orderDetail.put("subtotal", subtotal);
                    
                    // 将食品信息添加到映射中
                    foodMap.put(orderItem.getFoodId(), foodData);
                } else {
                    // 设置默认值
                    String defaultFoodName = "未知商品-" + orderItem.getFoodId();
                    itemDTO.setFoodName(defaultFoodName);
                    orderDetail.put("foodName", defaultFoodName);
                    
                    itemDTO.setFoodImg("");
                    orderDetail.put("foodImg", "");
                    
                    itemDTO.setFoodPrice(BigDecimal.TEN); // 默认价格10元
                    orderDetail.put("foodPrice", BigDecimal.TEN);
                    
                    itemDTO.setSubtotal(BigDecimal.TEN.multiply(new BigDecimal(orderItem.getQuantity())));
                    orderDetail.put("subtotal", BigDecimal.TEN.multiply(new BigDecimal(orderItem.getQuantity())));
                    
                    // 创建默认食品信息
                    Map<String, Object> defaultFoodInfo = new HashMap<>();
                    defaultFoodInfo.put("foodId", orderItem.getFoodId());
                    defaultFoodInfo.put("foodName", defaultFoodName);
                    defaultFoodInfo.put("foodPrice", BigDecimal.TEN);
                    defaultFoodInfo.put("foodImg", "");
                    
                    foodMap.put(orderItem.getFoodId(), defaultFoodInfo);
                }
            } catch (Exception e) {
                // 设置默认值
                String defaultFoodName = "未知商品-" + orderItem.getFoodId();
                itemDTO.setFoodName(defaultFoodName);
                orderDetail.put("foodName", defaultFoodName);
                
                itemDTO.setFoodImg("");
                orderDetail.put("foodImg", "");
                
                itemDTO.setFoodPrice(BigDecimal.TEN); // 默认价格10元
                orderDetail.put("foodPrice", BigDecimal.TEN);
                
                itemDTO.setSubtotal(BigDecimal.TEN.multiply(new BigDecimal(orderItem.getQuantity())));
                orderDetail.put("subtotal", BigDecimal.TEN.multiply(new BigDecimal(orderItem.getQuantity())));
                
                // 创建默认食品信息
                Map<String, Object> defaultFoodInfo = new HashMap<>();
                defaultFoodInfo.put("foodId", orderItem.getFoodId());
                defaultFoodInfo.put("foodName", defaultFoodName);
                defaultFoodInfo.put("foodPrice", BigDecimal.TEN);
                defaultFoodInfo.put("foodImg", "");
                
                foodMap.put(orderItem.getFoodId(), defaultFoodInfo);
                
                System.out.println("获取食品信息失败: " + e.getMessage());
            }
            
            orderItemDTOs.add(itemDTO);
            orderDetails.add(orderDetail);
        }
        
        orderDTO.setOrderItems(orderItemDTOs);
        
        // 设置额外的嵌套数据（兼容前端格式）
        orderDTO.setOrder(order);
        orderDTO.setMerchant(merchantInfo);
        orderDTO.setAddressInfo(addressInfo);
        orderDTO.setOrderDetails(orderDetails);
        orderDTO.setFoodMap(foodMap);
        
        return orderDTO;
    }
} 